package com.ideal.frame.template.service;

import com.ideal.frame.institutions.entity.InstitutionsOrganizationTb;
import com.ideal.frame.institutions.entity.QInstitutionsOrganizationTb;
import com.ideal.frame.jpa.JpaRepositoryImpl;
import com.ideal.frame.template.entity.AnalysisTemplate;
import com.ideal.frame.template.form.AnalysisTemplateForm;
import com.ideal.frame.template.repository.AnalysisTemplateRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author ybb
 * @Description
 * @Date 2021/9/7 17:05
 */
@Service
public class AnalysisTemplateService {

    @Autowired
    AnalysisTemplateRepository analysisTemplateRepository;

    public Page<AnalysisTemplate> pages(AnalysisTemplateForm searchForm){
        Specification<AnalysisTemplate> specification = new Specification<AnalysisTemplate>() {
            @Override
            public Predicate toPredicate(Root<AnalysisTemplate> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                if (StringUtils.isNoneBlank(searchForm.getTemplateName())){
                    predicates.add(cb.equal(root.get("templateName"),searchForm.getTemplateName()));
                }
                return cb.and(predicates.toArray(new Predicate[predicates.size()]));
            }

        };
        return analysisTemplateRepository.findAll(specification, PageRequest.of(searchForm.getPageNo()-1,searchForm.getPageSize()));
    }


    public AnalysisTemplate getOne(long id){
        return analysisTemplateRepository.findById(id).get();
    }

    public void add(AnalysisTemplate analysisTemplate){
        analysisTemplateRepository.save(analysisTemplate);
    }

    public void del( List<Long> ids){
        ids.forEach(id -> {
            analysisTemplateRepository.deleteById(id);
        });

    }

}
